package com.example.demo_bcos.controller;


import org.fisco.bcos.asset.client.AssetClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;

@RestController
@RequestMapping("/asset")
public class AssetClientController {

    private AssetClient client;
    private Boolean initFlag = false;

    /// 0. 初始化&部署合约
    private void init() throws Exception {
        client = new AssetClient();
        client.initialize();
        client.deployAssetAndRecordAddr();
        initFlag = true;
    }


    ///1. 注册账户
    @GetMapping("/register")
    public boolean registerAssetAccount(
            @RequestParam(value="account",required = true) String assetAccount,
            @RequestParam(value="amount",required = true) BigInteger amount) throws Exception {
        if(!initFlag) init();
        return client.registerAssetAccount(assetAccount, amount);
    }

    ///2. 查询余额
    @GetMapping("/query")
    public BigInteger queryAssetAmount(
            @RequestParam(value="account",required = true) String assetAccount) throws Exception {
        if(!initFlag) init();
        return client.queryAssetAmount(assetAccount);
    }

    ///2. 转账
    @GetMapping("/transfer")
    public boolean transferAsset(
            @RequestParam(value="from",required = true) String fromAssetAccount,
            @RequestParam(value="to",required = true) String toAssetAccount,
            @RequestParam(value="amount",required = true) BigInteger amount) throws Exception {
        if(!initFlag) init();
        return client.transferAsset(fromAssetAccount, toAssetAccount, amount);
    }

}

/**
 * http://localhost:8080/asset/register?account=Tom&amount=10000
 * http://localhost:8080/asset/register?account=Jerry&amount=10000
 *
 * http://localhost:8080/asset/query?account=Tom
 * http://localhost:8080/asset/query?account=Jerry
 *
 * http://localhost:8080/asset/transfer?from=Jerry&to=Tom&amount=100
 * */
